package com.tutu.controller;

import com.tutu.controller.common.CommonController;
import com.tutu.core.Constant;
import com.tutu.service.MasterService;
import com.tutu.service.RoleModuleService;
import com.tutu.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 初始化控制层
 */
@Controller
@RequestMapping(value = "")
public class IndexController extends CommonController {

    @Autowired
    MasterService masterService;

    @Autowired
    RoleModuleService roleModuleService;

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, String error, ModelMap model) {
        try {
            request.setCharacterEncoding(Constant.ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        masterService.loginOut(request);

        if (BaseUtil.isNotBlank(error)) model.addAttribute("error", error);

        return "login";
    }

    @RequestMapping(value = "/login/check")
    public String checkLogin(HttpServletRequest request, String account, String password, String verifyCode, ModelMap model) {
        try {
            request.setCharacterEncoding(Constant.ENCODING);

            String requestUrl = request.getRequestURL() + "";
            boolean isLocalhost = requestUrl.contains("localhost") || requestUrl.contains("127.0.0.1");

            // 如果是本地请求则直接跳过验证码校验逻辑
            if (!isLocalhost) {
                String baseCode = (String) request.getSession().getAttribute("verifyCode");

                if (BaseUtil.isBlank(verifyCode) || !verifyCode.equalsIgnoreCase(baseCode)) {
                    model.addAttribute("error", "验证码错误!");
                    return "redirect:/login";
                }
            }

            Map<String, Object> map = masterService.loginIn(request, account, password);

            if (null != map) {
                // 查询该管理员的所有菜单信息
                request.getSession().setAttribute(Constant.IS_LOCALHOST, isLocalhost);
                request.getSession().setAttribute(Constant.CURRENT_LOGIN_MODULE_LIST, roleModuleService.findListByMasterId(Integer.parseInt(map.get("id") + "")));

                return "redirect:/backend/dashboard";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("error", "用户名或密码错误");
        return "redirect:/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        masterService.loginOut(request);
        return "login";
    }

    @RequestMapping(value = "/")
    public String index(HttpServletRequest request) {
        if (null != WebUtil.getSysInfo(request, Constant.CURRENT_LOGIN_MASTER_ID)) {
            return "redirect:/backend/dashboard";
        } else {
            masterService.loginOut(request);
            return "login";
        }
    }

    /**
     * 检测当前登录人旧密码是否正确
     */
    @RequestMapping("/check/oldPwd")
    @ResponseBody
    public Integer checkOldPwd(HttpServletRequest request, String oldPwd) {
        Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(Constant.CURRENT_LOGIN_MASTER);

        if (!map.containsKey("password") || !map.get("password").equals(Md5Util.md5(oldPwd))) {
            return 0;
        } else {
            return 1;
        }
    }

    @RequestMapping("/modifyPwd")
    @ResponseBody
    public Map<String, Object> modifyPwd(HttpServletRequest request, String newPwd) {
        return masterService.modifyPwd(request, newPwd);
    }

    @RequestMapping(value = "/getVerifyCode")
    @ResponseBody
    public static Map<String, Object> getVerifyCode(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String code = GenerateCodeUtil.getVerifyCode();

        map.put("code", code);
        map.put("content", Img2Base64Util.getImgStr(Constant.VERIFY_CODE_URL));

        // 将生成的验证码的值放到session中去
        if (null != request) request.getSession().setAttribute("verifyCode", code);

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/MP_verify_KUs5fL6XnKKAAhNk.txt")
    public void getAuthFile(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        try {
            // 防止中文乱码
            response.setContentType("text/plain;charset=utf-8");
            response.setCharacterEncoding(Constant.ENCODING);

            // 可以捕获内存缓冲区【生成的图片在缓冲区里面】的数据，将数据装换成字节数组，输出流的缓冲区的大小会随着数据的不断写入而自动增加
            // 使用toByteArray()和toString()获得生成字节数组的数据
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            output.write(Objects.requireNonNull(FileUploadUtils.getFileBytes("E://apache-tomcat-7.0.88/webapps/ROOT/MP_verify_KUs5fL6XnKKAAhNk.txt")));

            // servlet程序想servletOutputStream或PrintWriter对象中写入数据将被servlet引擎从response中获得
            ServletOutputStream out = response.getOutputStream();

            // 将byte数组输出流的全部内容写到指定的输出流参数中
            output.writeTo(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}